package com.kancy.springcloudconfig.action;

import com.kancy.springcloudconfig.action.model.AlgorithmData;
import com.kancy.springcloudconfig.action.model.RefreshObject;
import com.kancy.springcloudconfig.constants.Constants;
import com.kancy.springcloudconfig.exception.AlertException;
import com.kancy.springcloudconfig.util.CommonUtil;
import com.kancy.springcloudconfig.util.KmsUtil;

/**
 * <p>
 * CipherAlgorithAction
 * </p>
 *
 * @author: kancy
 * @date: 2019/10/26 14:09
 **/
public class KmsAlgorithAction extends AbstractAlgorithmAction {
    /**
     * 检查数据
     *
     * @param data
     */
    @Override
    protected void checkAlgorithmData(AlgorithmData data) {
        super.checkAlgorithmData(data);
        // 默认值
        if(CommonUtil.isEmpty(data.getPassword())){
            throw new AlertException("请输入ID！");
        }
        if(CommonUtil.isEmpty(data.getSalt())){
            throw new AlertException("请输入KEY！");
        }
        if(data.getSalt().length() % 16 != 0){
            throw new AlertException("输入KEY不合法，key长度为："+data.getSalt().length() +"！");
        }
    }

    /**
     * 解密逻辑
     *
     * @param data
     */
    @Override
    protected String decrypt(AlgorithmData data) {
        return KmsUtil.decrypt(data.getPassword(), data.getSalt(), data.getCipherText().trim());
    }

    /**
     * 加密逻辑
     *
     * @param data
     */
    @Override
    protected String encrypt(AlgorithmData data) {
        return KmsUtil.encrypt(data.getPassword(), data.getSalt(), data.getPlainText().trim());
    }

    @Override
    protected void update(RefreshObject object) {
        object.getPasswordObject().setVisible(true);
        object.getPasswordObject().setText(Constants.DEFAULT_KMS_ID);
        object.getSaltObject().setVisible(true);
        object.getSaltObject().setText(Constants.DEFAULT_KMS_KEY);
        object.getLabel1Object().setVisible(true);
        object.getLabel1Object().setText("ID:");
        object.getLabel2Object().setVisible(true);
        object.getLabel2Object().setText("KEY:");
    }

}
